"""
用户认证相关API
提供登录、登出、用户信息获取等接口
"""
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import json


def json_response(success=True, message='', data=None, status=200):
    """统一JSON响应格式"""
    return JsonResponse({
        'success': success,
        'message': message,
        'data': data or {}
    }, status=status)


@csrf_exempt
@require_http_methods(["POST"])
def user_login(request):
    """
    用户登录接口
    POST /xinshi/auth/login
    参数: username, password
    """
    try:
        body = json.loads(request.body)
        username = body.get('username')
        password = body.get('password')
        
        if not username or not password:
            return json_response(
                success=False, 
                message='用户名和密码不能为空',
                status=400
            )
        
        # 验证用户
        user = authenticate(request, username=username, password=password)
        
        if user is not None:
            # 登录成功
            login(request, user)
            return json_response(
                success=True,
                message='登录成功',
                data={
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'first_name': user.first_name,
                    'last_name': user.last_name,
                    'is_staff': user.is_staff,
                    'is_active': user.is_active,
                }
            )
        else:
            return json_response(
                success=False,
                message='用户名或密码错误',
                status=401
            )
            
    except json.JSONDecodeError:
        return json_response(
            success=False,
            message='请求数据格式错误',
            status=400
        )
    except Exception as e:
        return json_response(
            success=False,
            message=f'登录失败: {str(e)}',
            status=500
        )


@require_http_methods(["GET"])
def user_info(request):
    """
    获取当前用户信息
    GET /xinshi/auth/info
    """
    if not request.user.is_authenticated:
        return json_response(
            success=False,
            message='未登录',
            status=401
        )
    
    user = request.user
    
    # 尝试获取用户心理档案
    user_profile = None
    try:
        from ai_chat.models import UserProfile
        user_profile = UserProfile.objects.filter(user=user).first()
    except:
        pass
    
    data = {
        'id': user.id,
        'username': user.username,
        'email': user.email,
        'first_name': user.first_name,
        'last_name': user.last_name,
        'is_staff': user.is_staff,
        'is_active': user.is_active,
        'date_joined': user.date_joined.strftime('%Y-%m-%d %H:%M:%S'),
    }
    
    # 添加心理档案信息
    if user_profile:
        data['profile'] = {
            'age': user_profile.age,
            'gender': user_profile.gender,
            'occupation': user_profile.occupation,
            'privacy_level': user_profile.privacy_level,
        }
    
    return json_response(
        success=True,
        message='获取用户信息成功',
        data=data
    )


@csrf_exempt
@require_http_methods(["POST"])
def user_logout(request):
    """
    用户登出接口
    POST /xinshi/auth/logout
    """
    try:
        logout(request)
        return json_response(
            success=True,
            message='登出成功'
        )
    except Exception as e:
        return json_response(
            success=False,
            message=f'登出失败: {str(e)}',
            status=500
        )


@csrf_exempt
@require_http_methods(["POST"])
def user_register(request):
    """
    用户注册接口
    POST /xinshi/auth/register
    参数: username, password, email, first_name, last_name
    """
    try:
        body = json.loads(request.body)
        username = body.get('username')
        password = body.get('password')
        email = body.get('email', '')
        first_name = body.get('first_name', '')
        last_name = body.get('last_name', '')
        
        if not username or not password:
            return json_response(
                success=False,
                message='用户名和密码不能为空',
                status=400
            )
        
        # 检查用户名是否已存在
        if User.objects.filter(username=username).exists():
            return json_response(
                success=False,
                message='用户名已存在',
                status=400
            )
        
        # 创建用户
        user = User.objects.create_user(
            username=username,
            password=password,
            email=email,
            first_name=first_name,
            last_name=last_name
        )
        
        # 自动创建心理档案
        try:
            from ai_chat.models import UserProfile
            UserProfile.objects.create(user=user)
        except:
            pass
        
        return json_response(
            success=True,
            message='注册成功',
            data={
                'id': user.id,
                'username': user.username,
                'email': user.email,
            }
        )
        
    except json.JSONDecodeError:
        return json_response(
            success=False,
            message='请求数据格式错误',
            status=400
        )
    except Exception as e:
        return json_response(
            success=False,
            message=f'注册失败: {str(e)}',
            status=500
        )


@require_http_methods(["GET"])
def check_auth(request):
    """
    检查用户登录状态
    GET /xinshi/auth/check
    """
    return json_response(
        success=True,
        message='认证状态检查成功',
        data={
            'is_authenticated': request.user.is_authenticated,
            'username': request.user.username if request.user.is_authenticated else None
        }
    )
